<template>
  <div class="app-container">
    <h2 style="text-align: center">发布新课程</h2>
    <el-steps
      :active="2"
      align-center
      style="margin-bottom: 40px"
      process-status="wait"
    >
      <el-step title="填写课程基本信息"></el-step>
      <el-step title="创建课程大纲"></el-step>
      <el-step title="发布课程"></el-step>
    </el-steps>
    <el-button type="text" @click="openAddChapterDialog">添加章节</el-button>
    <ul class="chanpterList">
      <li v-for="chapter in chapterNestedList" :key="chapter.id">
        <p>
          {{ chapter.title }}
          <span class="acts">
            <el-button type="text" @click="openAddVideoDialog(chapter.id)"
              >添加课时</el-button
            >
            <el-button type="text" @click="openEditChapterDialog(chapter.id)"
              >编辑</el-button
            >
            <el-button type="text" @click="deleteChapter(chapter.id)"
              >删除</el-button
            >
          </span>
        </p>
        <ul class="chanpterList videoList">
          <li v-for="video in chapter.children" :key="video.id">
            <p>
              {{ video.title }}
              <span class="acts">
                <el-button type="text" @click="openEditVideoDialog(video.id)"
                  >编辑</el-button
                >
                <el-button type="text" @click="deleteVideo(video.id)"
                  >删除</el-button
                >
              </span>
            </p>
          </li>
        </ul>
      </li>
    </ul>
    <el-button type="default" @click="privious()">上一步</el-button>

    <el-button type="primary" @click="next()">下一步</el-button>
    <!-- 添加/编辑章节表单对话框 -->
    <el-dialog :title="dialogCapterTitle" :visible.sync="dialogChapterVisible">
      <el-form :model="chapter" :rules="chapterRules" ref="chapterForm">
        <el-form-item label="章节标题" prop="title">
          <el-input v-model="chapter.title" />
        </el-form-item>
        <el-form-item label="章节排序" prop="sort">
          <el-input-number
            v-model="chapter.sort"
            controls-position="right"
            :min="0"
          >
          </el-input-number>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogChapterVisible = false">取 消</el-button>
        <el-button type="chapter" @click="submitChapter">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 添加/编辑课时表单对话框 -->
    <el-dialog :title="dialogVideoTitle" :visible.sync="dialogVideoVisible">
      <el-form :model="video" :rules="videoRules" ref="videoForm">
        <el-form-item label="课时标题" prop="title">
          <el-input v-model="video.title" />
        </el-form-item>
        <el-form-item label="课时排序" prop="sort">
          <el-input-number
            v-model="video.sort"
            controls-position="right"
            :min="0"
          >
          </el-input-number>
        </el-form-item>
        <el-form-item label="是否免费">
          <el-radio v-model="video.isFree" :label="1">免费</el-radio>
          <el-radio v-model="video.isFree" :label="0">收费</el-radio>
        </el-form-item>
        <el-form-item label="上传视频">
          <el-upload
            class="upload-demo"
            :action="`${BASE_URL}/vod/upload`"
            :on-success="handlUpload"
            :on-remove="handleRemove"
            :before-remove="beforeRemove"
            :limit="1"
            :on-exceed="handleExceed"
            :file-list="fileList"
          >
            <el-button type="primary" size="mini">上传视频</el-button>
            <el-tooltip class="item" effect="dark" placement="right-end">
              <div slot="content">
                最大支持1G，<br />支持3Gp、ASF、AVI、DAT、DV、FLV、F4V<br />、GIF、M2T、M4V、MJ2、MJPEG、MKV、
                MOV、MP4<br />、MPE、MPG、MPEG、MTS、OGG、QT、RM、RMVB<br />、SWF、TS、VOB、WMV、WEBM等视频格式上传
              </div>
              <i class="el-icon-question"></i>
            </el-tooltip>
          </el-upload>
        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVideoVisible = false">取 消</el-button>
        <el-button type="chapter" @click="submitVideo">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
import chapterApi from "@/api/chapter";
import videoApi from "@/api/video";
import vodApi from "@/api/vod"
export default {
  data() {
    return {
      BASE_URL: process.env.BASE_API, //获取dev配置文件中的API地址
      fileList: [], //上传文件的列表
      courseId: "", //课程id
      chapterNestedList: [], //课程大纲列表
      dialogChapterVisible: false, //添加章节对话框
      dialogVideoVisible: false, //课程小结对话框
      chapter: {
        courseId: "",
        title: "",
        sort: 0,
      },
      video: {
        courseId: "",
        chapterId: "",
        title: "",
        videoSourceId: "",
        videoOriginalName: "",
        sort: 0,
        isFree: 0,
      },
      dialogCapterTitle: "", //课程章节对话框标题
      dialogVideoTitle: "", //课程小结对话框标题
      chapterRules: {
        // 章节表单验证
        title: [
          { required: true, message: "请输入章节标题", trigger: "blur" },
          { max: 50, message: "长度最大 50 个字符", trigger: "blur" },
        ],
        sort: [
          { type: "number", message: "排序必须是数字", trigger: "blur" },
          { required: true, message: "请输入序号", trigger: "blur" },
        ],
      },

      videoRules: {
        // 课时表单验证
        title: [
          { required: true, message: "请输入课时标题", trigger: "blur" },
          { max: 50, message: "长度最大 50 个字符", trigger: "blur" },
        ],
        sort: [
          { type: "number", message: "排序必须是数字", trigger: "blur" },
          { required: true, message: "请输入序号", trigger: "blur" },
        ],
      },
    };
  },

  created() {
    // 初始化课程大纲
    this.init();
  },
  methods: {
    handleRemove(file, fileList) {
      console.log(file, fileList);
      // 调用删除API
      vodApi.deleteVod(this.video.videoSourceId).then(res=>{
        // 清空视频信息
        this.video.videoSourceId=""
        this.video.videoOriginalName=""
        this.fileList=[]

        // 提示信息

          this.$message({
              type: "success",
              message: "删除成功!",
            });
      })
    },
    handleExceed(files, fileList) {
      this.$message.warning(
        `上传失败最大上传一个视频，如果想要再次上传请先删除`
      );
    },
    beforeRemove(file, fileList) {
      return this.$confirm(`确定移除 ${file.name}？`);
    },
    handlUpload(response, file, fileList) {
      console.log(response);
      console.log(file);
      console.log(fileList);
      // 获取视频编号
      this.video.videoSourceId = response.data.videoSourceId;

      // 获取视频原始名称
      this.video.videoOriginalName = file.name;
    },
    // 上一步
    privious() {
      this.$router.push({ path: `/coures/info/${this.courseId}` });
    },
    // 下一步
    next() {
      this.$router.push({
        name: "CouresInfoPublish",
        params: { id: this.courseId },
      });
    },
    // 打开添加课时对话框
    openAddVideoDialog(chapterId) {
      this.dialogVideoTitle = "添加课时";
      this.dialogVideoVisible = true;

      this.fileList = [];

      // 为课时的章节id赋值
      // this.video.chapterId = chapterId;

      //  清空表单数据
      this.video = {
        id: "",
        courseId: "",
        chapterId: chapterId,
        title: "",
        videoSourceId: "",
        videoOriginalName: "",
        sort: 0,
        isFree: 0,
      };
    },
    // 根据id删除
    deleteChapter(chapterId) {
      // 弹出对话框是否删除
      this.$confirm("您确定要删除该章节吗?", "温馨提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          // 调用删除API
          // console.log("111");
          chapterApi.deleteById(chapterId).then((res) => {
            console.log(res);
            this.$message({
              type: "success",
              message: "删除成功!",
            });
            // 更新数据
            this.init();
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    deleteVideo(videoId) {
      // 弹出对话框是否删除
      this.$confirm("您确定要删除该课时吗?", "温馨提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          // 调用删除API
          // console.log("111");
          videoApi.deleteById(videoId).then((res) => {
            console.log(res);
            this.$message({
              type: "success",
              message: "删除成功!",
            });
            // 更新数据
            this.init();
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    // 更新课程章节
    updateChapter() {
      // 调用更新课程章节的API
      chapterApi.updateChapter(this.chapter).then((res) => {
        // 更新成功提示信息
        this.$message({
          type: "success",
          message: "更新成功！",
        });
        // 关闭课程章节对话框
        this.dialogChapterVisible = false;
        // 重置视频上传列表
        this.fileList = [];
        //  重新加载
        this.init();
      });
    },
    // 更新课时
    updateVideo() {
      // 调用更新课时章节的API
      videoApi.updateVideo(this.video).then((res) => {
        // 更新成功提示信息
        this.$message({
          type: "success",
          message: "更新成功！",
        });
        // 关闭课时章节对话框
        this.dialogVideoVisible = false;
        //  重新加载
        this.init();
      });
    },
    // 打开编辑课程章节对话框
    openEditChapterDialog(chapterId) {
      this.dialogCapterTitle = "编辑章节";
      // 根据章节id获取章节信息
      chapterApi.getChapter(chapterId).then((res) => {
        this.chapter = res.data;
        // 打开章节对话框
        this.dialogChapterVisible = true;
      });
    },
    // 打开编辑课时对话框
    openEditVideoDialog(videoId) {
      this.dialogCapterTitle = "编辑课时";
      this.fileList = [];
      // 根据id查询课时信息
      videoApi.getVideoByid(videoId).then((res) => {
        this.video = res.data;
        if (this.video.videoOriginalName) {
          // 为上传视频列表对象赋值
          this.fileList = [{ name: this.video.videoOriginalName }];
        }
        // 打开课时表单对话框
        this.dialogVideoVisible = true;
      });
    },
    // 提交章节对话框表单数据
    submitChapter() {
      // 进行数据的合法性校验
      this.$refs["chapterForm"].validate((valid) => {
        if (valid) {
          // 格式校验通过
          // 判断添加还是更新
          if (this.chapter.id) {
            //  调用更新
            this.updateChapter();
            // console.log("11111")
          } else {
            console.log("执行添加");
            //  调用添加
            this.addChapter();
          }
        } else {
          // 格式校验失败
          console.log("error submit!!");
          return false;
        }
      });
    },
    // 提交课时表单对话框
    submitVideo() {
      // 进行数据的合法性校验
      this.$refs["videoForm"].validate((valid) => {
        if (valid) {
          // 格式校验通过
          // 判断添加还是更新
          if (this.video.id) {
            //  调用更新
            this.updateVideo();
          } else {
            console.log("执行添加");
            //  调用添加
            this.addVideo();
          }
        } else {
          // 格式校验失败
          console.log("error submit!!");
          return false;
        }
      });
    },
    // 添加章节
    addChapter() {
      // 为课程id赋值
      this.chapter.courseId = this.courseId;
      // 调用添加课程章节的api
      chapterApi.addChapter(this.chapter).then((res) => {
        // 提示成功信息
        this.$message({
          type: "success",
          message: "添加成功！",
        });
        // 关闭对话框
        this.dialogChapterVisible = false;
        // 更新数据
        this.init();
      });
    },
    // 添加课时
    addVideo() {
      // 为课程id赋值
      this.video.courseId = this.courseId;

      // 调用课时的API
      videoApi.addVideo(this.video).then((res) => {
        // 提示成功信息
        this.$message({
          type: "success",
          message: "添加成功！",
        });
        // 关闭对话框
        this.dialogVideoVisible = false;
        // 更新数据
        this.init();
      });
    },
    // 打开添加章节对话框
    openAddChapterDialog() {
      this.dialogCapterTitle = "编辑章节";
      this.dialogChapterVisible = true;

      // 初始化章节表单信息
      this.chapter = {
        title: "",
        sort: 0,
        id: "",
      };
    },
    // 初始化课程大纲
    init() {
      if (this.$route.params && this.$route.params.id) {
        // 根据课程id获取当前要更新课程信息
        // 绑定到页面中
        this.courseId = this.$route.params.id;
        // console.log(courseId);
        this.getChapterTree(this.courseId);
      }
    },
    // 获取课程大纲
    getChapterTree(courseId) {
      chapterApi.getTreeList(courseId).then((res) => {
        // console.log(res);
        this.chapterNestedList = res.data;
      });
    },
  },
};
</script>

<style scoped>
.chanpterList {
  position: relative;
  list-style: none;
  margin: 0;
  padding: 0;
}
.chanpterList li {
  position: relative;
}
.chanpterList p {
  float: left;
  font-size: 20px;
  margin: 10px 0;
  padding: 10px;
  height: 70px;
  line-height: 50px;
  width: 100%;
  border: 1px solid #ddd;
}
.chanpterList .acts {
  float: right;
  font-size: 14px;
}

.videoList {
  padding-left: 50px;
}
.videoList p {
  float: left;
  font-size: 14px;
  margin: 10px 0;
  padding: 10px;
  height: 50px;
  line-height: 30px;
  width: 100%;
  border: 1px dotted #ddd;
}
</style>
